package com.lovo.csc.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lovo.csc.entity.Deposit;
import com.lovo.csc.entity.Prepay;
import com.lovo.csc.service.IDepositService;
import com.lovo.csc.service.IPrepayService;
import com.lovo.util.MQUtil;
import io.swagger.annotations.Api;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * <p>
 * 每次存款的记录 前端控制器
 * </p>
 *
 * @author lovo
 * @since 2022-07-07
 */
@RestController
@RequestMapping("/deposit")
@Api(tags = "存款操作层")
public class DepositController {
    @Autowired
    IDepositService service;
    @Autowired
    IPrepayService prepayService;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @PostMapping("depositMoney")
    public boolean addMembership(String userCode,float money,String way){
        Deposit deposit=new Deposit();
        // 得到预存款表的编号
        QueryWrapper<Prepay> qw= new QueryWrapper<>();
        qw.eq("user_code",userCode);
        Prepay prepay=prepayService.getOne(qw);
        if (prepay == null){
            prepay=new Prepay();
            prepay.setUserCode(userCode);
            prepay.setBalance(money);
        }else {
            prepay.setBalance(prepay.getBalance()+money);
        }
        //添加余额或新建用户，保存
        prepayService.saveOrUpdate(prepay);
        //充值记录的设置
        deposit.setPrepayId(prepay.getPrepayId());
        deposit.setUserCode(userCode);
        deposit.setSaveMoney(money);
        deposit.setSaveWay(way);
        DateTimeFormatter df=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        deposit.setSaveTime(df.format(LocalDateTime.now()));
        // 这里充值成功，通知前端
//        rabbitTemplate.convertAndSend(MQUtil.PrepayExchange,MQUtil.depositKey,userCode+"  "+money);
        return service.save(deposit);
    }
}
